package com.kzj.xfxh.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kzj.common.constant.GlobalConstant;
import com.kzj.common.exception.XfxhApiException;
import com.kzj.xfxh.entity.JsonParse;
import com.kzj.xfxh.entity.RoleContent;
import com.kzj.xfxh.entity.Text;
import com.kzj.xfxh.properties.XfxhProperties;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
@Scope("prototype")
public class XfxhApiPlus extends WebSocketListener {
    @Autowired
    XfxhProperties xfxhProperties;
    private static List<RoleContent> historyList=new ArrayList<>(); // 对话历史存储集合
    private static final Gson gson = new Gson();
    public  String question = null;
    public  String answer=null; // 大模型的答案汇总
    private Boolean answerCompleteFlag=true;
    private String userId="kzj";
    public String ask(String content)
    {
        question=content;
        // 构建鉴权url
        String authUrl = null;
        try {
            authUrl = getAuthUrl();
        } catch (Exception e) {
            throw new XfxhApiException(GlobalConstant.WAIT_A_MOMENT);
        }
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();
        answer="";
        if(answerCompleteFlag==false)
            throw new XfxhApiException(GlobalConstant.WAIT_A_MOMENT);
        answerCompleteFlag=false;
        client.newWebSocket(request,this);
        while(true)
        {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if(answerCompleteFlag)
                break;
        }
            return answer;

    }

    class MyThread extends Thread {
        private WebSocket webSocket;

        public MyThread(WebSocket webSocket) {
            this.webSocket = webSocket;
        }
        public void run() {
            log.info("讯飞星火api 启动");
            try {
                JSONObject requestJson=new JSONObject();

                JSONObject header=new JSONObject();  // header参数
                header.put("app_id",xfxhProperties.getAppId());
                header.put("uid",userId);

                JSONObject parameter=new JSONObject(); // parameter参数
                JSONObject chat=new JSONObject();
                chat.put("domain",xfxhProperties.getDomain());
                chat.put("temperature",xfxhProperties.getTemperature());
                chat.put("max_tokens",xfxhProperties.getMaxTokens());
                parameter.put("chat",chat);

                JSONObject payload=new JSONObject(); // payload参数
                JSONObject message=new JSONObject();
                JSONArray text=new JSONArray();

                // 历史问题获取
                if(historyList.size()>0){
                    for(RoleContent tempRoleContent:historyList){
                        text.add(JSON.toJSON(tempRoleContent));
                    }
                }

                // 最新问题
                RoleContent roleContent=new RoleContent();
                roleContent.role="user";
                roleContent.content=question;
                text.add(JSON.toJSON(roleContent));
                historyList.add(roleContent);


                message.put("text",text);
                payload.put("message",message);


                requestJson.put("header",header);
                requestJson.put("parameter",parameter);
                requestJson.put("payload",payload);
                log.info(requestJson.toString()); // 可以打印看每次的传参明细
                webSocket.send(requestJson.toString());
                // 等待服务端返回完毕后关闭
                while (true) {
                    Thread.sleep(50);
                    if (answerCompleteFlag) {
                        break;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            }
    }
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        MyThread myThread = new MyThread(webSocket);
        myThread.start();
    }
    public void webSocketClose(WebSocket webSocket)
    {
        webSocket.close(1000, "");
    }
    @Override
    public void onMessage(WebSocket webSocket, String text) {
        System.out.println(text);
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
        if (myJsonParse.header.code != 0) {
            log.error("发生错误，错误码为：" + myJsonParse.header.code);
            log.error("本次请求的sid为：" + myJsonParse.header.sid);
            webSocketClose(webSocket);
        }
        List<Text> textList = myJsonParse.payload.choices.text;
        for (Text temp : textList) {
            answer=answer+temp.content;
        }
        if (myJsonParse.header.status == 2) {
            log.info("回答结束\n**********************************************************************************************");
            if(canAddHistory()){
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(answer);
                historyList.add(roleContent);
            }else{
                historyList.remove(0);
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(answer);
                historyList.add(roleContent);
            }
            answerCompleteFlag=true;
            webSocketClose(webSocket);
        }

    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (null != response) {
                int code = response.code();
                log.error("onFailure code:" + code);
                log.error("onFailure body:" + response.body().string());
                if (101 != code) {
                    log.error("connection failed");
                    throw new XfxhApiException("connection failed");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private   static boolean canAddHistory(){  // 由于历史记录最大上线1.2W左右，需要判断是能能加入历史
        int history_length=0;
        for(RoleContent temp:historyList){
            history_length=history_length+temp.content.length();
        }
        if(history_length>12000){
            historyList.remove(0);
            historyList.remove(1);
            historyList.remove(2);
            historyList.remove(3);
            historyList.remove(4);
            return false;
        }else{
            return true;
        }
    }
    private String getAuthUrl() throws MalformedURLException, NoSuchAlgorithmException, InvalidKeyException {
        URL url = new URL(xfxhProperties.getHostUrl());
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(xfxhProperties.getApiSecret().getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", xfxhProperties.getApiKey(), "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();
        return httpUrl.toString();
    }
}